import puppeteer from 'puppeteer';
import xlsx from 'node-xlsx';
import GoLogin from '../src/gologin.js';
import readline from 'readline';
import fs from 'fs';
import request from 'request';
import { authenticator } from 'otplib';
import random from 'random-js';
import path from 'path';
import { spawn } from 'child_process';
import axios from 'axios';
import fueldo from '../my-electron-app/fueldo.js';

let isRandomMove = true;
(async () => {
  // await refreshAccount('!383157zhangHAO',0)
  // startGame('');
  await getBrowser()
})();

async function exportAddresses(psw) {


  fs.mkdir('c://fuel', { recursive: true }, (err) => {
    if (err) {
      console.error(err);
      return;
    }
    console.log('文件夹创建成功');
  });

  let browser = await getBrowser();
  let newPage = await browser.newPage();
  await gotoAddresses(newPage, psw);
  //选地址
  const items = await newPage.$$(
    '.fuel_CardList>article>.fuel_Box-flex>.fuel_Box-flex',
  );
  const data = new Array();
  for (const item of items) {
    const name = await item.$(
      'h6',
    );
    const address = await item.$(
      'p',
    );

    const nameText = await newPage.evaluate(a => a.innerText, name);
    const addresstext = await newPage.evaluate(a => a.innerText, address);
    if (addresstext.startsWith('0x')) {
      data.push([nameText, addresstext]);
    }
  }
  console.log(data.toString());

  const list = [
    {
      name: '地址', // 工作薄的名称
      data: data,
    },
  ];

  const buffer = xlsx.build(list);
  let result = false;
  await fs.writeFile(path, buffer, function (err) {
    if (err) {
      console.log(err, '导出excel失败');
    } else {
      console.log('导出excel成功!');
      result = true;
    }

  });
  await sleep(3000);
  newPage.close();
  return result;
}

// promise[0].goto('h');
// const elementHandle = await page.$(
//   'input[inputmode="decimal"]',
// );
// await elementHandle.click({ clickCount: 3 })
// await elementHandle.type('0.0001',{ delay: 100 });
//
// const btn = await page.$(
//   'article+button',
// );
// await btn.click();
//
// try {
//   const div = await page.$(
//     'div[tabindex="1"]',
//   );
//   await div.click();
// } catch (e) {
//   await sleep(3000);
// }
//
// pages = await browser.pages();
// const div2 = await pages[0].$(
//   'button[type="submit"]',
// );
// await div2.click();
// await sleep(1000);
// const sum2 = await pages[0].$(
//   'button[type="submit"]',
// );
// await sum2.click();

//番茄
// await connect();
//
// await chooseWallet(browser,6);

// await refreshAccount(browser);

// pages = await browser.pages();
// const div2 = await pages[0].$(
//   'button[type="submit"]',
async function refreshAccount(psw, currentItem) {
  let browser = await getBrowser();
  let pages = await browser.pages();
  for (let i = 1; i < pages.length; i++) {
    await pages[i].close();
  }
  isRandomMove = true;
  const newPage = await browser.newPage();
  await unlock(newPage, psw);
  await disConnect(newPage, psw);

  await gotoAddresses(newPage, psw);
  //选地址

  const addresses = await newPage.$$(
    '.fuel_Box-flex>.fuel_Box-flex>.fuel_Box-flex>.address',
  );

  const sheets = xlsx.parse(path);
  console.log('ca' + currentItem);
  const sheetElement = sheets[0].data[currentItem];
  const excuAddress = sheetElement[1].trim();

  for (const address of addresses) {
    const addresstext = await newPage.evaluate(ads => ads.textContent, address);
    console.log(addresstext + '---' + excuAddress);

    if (addresstext.trim() === excuAddress.trim()) {

      await address.click();
    }
  }

  await sleep(5000);
  // await newPage.close();
  return excuAddress;
  //领水

  // const btns = await newPage.$$(
  //   'button[intent="primary"]',
  // );
  // for (const btn of btns) {
  //   const btntext = await newPage.evaluate(btn => btn.textContent, btn);
  //
  //   if (btntext.includes('Faucet')){
  //     await btn.click();
  //   }
  // }

  // await newPage.close();
}

// );

async function chooseWay(page) {

}

async function startGame(psw) {
  let browser = await getBrowser();

  let newPage = await browser.newPage();
  await newPage.goto('https://www.swayfarm.xyz/');
  await sleep(2000);
  try {
    const btnas = await newPage.$(
      '.c-iPYhUp-ikYuPBS-css>button',
    );
    await btnas.click();
    await sleep(800);
    const div = await newPage.$(
      'div[tabindex="1"]',
    );
    await sleep(800);
    await div.click();
  } catch (e) { /* empty */
  }
  //在点击按钮之前，事先定义一个promise，用于返回新tab的page对象
  // const newPagePromise = new Promise(res =>
  //   browser.once('targetcreated',
  //     target => res(target.page()),
  //   ),
  // );
  // await div.click();
  // let newPage2 = await newPagePromise;
  // await chooseWallet(newPage2, psw);
  clickApprove(browser, psw);

  await move(newPage);
// await chooseWallet(browser);
// await move(browser);

  // randomMove(newPage);
}

async function randomMove(page) {
  for (let i = 0; i < 1;) {
    if (isRandomMove) {
      let randomNumber = Math.floor((Math.random() * 5) + 1);
      switch (randomNumber) {
        case 1:
          await rabMove(page, 'ArrowUp');
          break;
        case 2:
          await rabMove(page, 'ArrowRight');
          break;
        case 3:
          await rabMove(page, 'ArrowDown');
          break;
        case 4:
          await rabMove(page, 'ArrowLeft');
          break;
        case 5:
          await rabMove(page, 'ArrowDown');
          break;
      }
    }
    await sleep(300);
  }

}

async function moveToSell(page) {
  isRandomMove = false;
  for (let i = 0; i < 8; i++) {
    await rabMove(page, 'ArrowRight');
    await rabMove(page, 'ArrowUp');
  }
  await rabMove(page, 'ArrowLeft');

}

async function clickOpt(page) {
  // for (let i = 0; i < 1;) {
  try {
    const plant = await page.$(
      '.plant-modal',
    );
    if (plant !== null) {
      const plantText = await page.evaluate(plant => plant.textContent, plant);
      if (plantText.startsWith('You don\'t')) {
        await moveToSell(page);
      }
    }
    const zz = await page.$(
      'img[src="images/tomato_seed_bag.png"]+div',
    );
    const zzs = await page.evaluate(zz => zz.textContent, zz);
    console.log(zzs);

    const cs = await page.$(
      'img[src="images/tomato.png"]+div',
    );
    const css = await page.evaluate(cs => cs.textContent, cs);
    console.log(css);

    const btn2 = await page.$$(
      'button',
    );
    let btn2Element = btn2[0];
    const btntext = await page.evaluate(btn2Element => btn2Element.textContent, btn2Element);
    if (btntext.startsWith('Buy')) {
      if (zzs < 10) {
        await btn2[0].click();
      }
      if (css > 0) {
        await btn2[1].click();
      }
      isRandomMove = true;
    } else {
      await btn2Element.click();
    }
  } catch (e) {
    // console.log(e);
  }
  await sleep(300);
  // }
}

async function clickApprove(browser, psw) {

  for (let i = 0; i < 1;) {
    try {
      const pages = await browser.pages();

      for (const page of pages) {
        const title = await page.title();
        console.log(title);
        if (title.includes('Fuel')) {
          const btn = await page.$(
            'button[intent="primary"]',
          );
          const gameName = await page.evaluate(btn => btn.textContent, btn);
          if (gameName.includes('Unlock')) {
            const pass = await page.$(
              'input[type="password"]',
            );
            await pass.click({ clickCount: 3 });
            await pass.type(psw);
          }
          if (!gameName.includes('Send')) {
            await btn.click();
          }
        }
      }

    } catch (e) { /* empty */
      console.log(e);
    }

    await sleep(3000);
  }
}

async function move(page) {
  for (let i = 0; i < 4; i++) {
    await rabMove(page, 'ArrowDown');
  }
  await rabMove(page, 'ArrowRight');
  randomMove(page);
}

async function chooseWallet(newPage, psw) {
  console.log('8888888');

  await unlock(newPage, psw);
  await sleep(3000);

  try {
    const div2 = await newPage.$(
      'button[intent="primary"]',
    );

    await div2.click();
  } catch (e) {
    console.log(e);
    await sleep(3000);
  }
  await sleep(6000);

  // await newPage.$(
  //   'div[aria-label="Confirm Transaction"]',
  // );
  const btn = await newPage.$(
    'button[intent="primary"]',
  );
  await btn.click();
}

async function rabMove(page, way) {
  await page.keyboard.down(way);
  await sleep(300);
  await page.keyboard.up(way);
  // await sleep(500);
  await clickOpt(page);

}

async function getBrowser() {
  let wsKey = await axios.get('http://localhost:9222/json/version');
  let browser = await puppeteer.connect({
    browserWSEndpoint: wsKey.data.webSocketDebuggerUrl,
    defaultViewport: null,
  });

  return browser;
}

async function gotoAddresses(newPage, psw) {
  await newPage.goto('chrome-extension://dldjpboieedgcmpkchcjcbijingjcgok/popup.html#/wallet');

  await unlock(newPage, psw);
  await sleep(3000);
  const accs = await newPage.$(
    'button[aria-label="Accounts"]',
  );
  await accs.click();

  return newPage;
}

async function unlock(newPage, psw) {
  try {
    const btn = await newPage.$(
      'button[intent="primary"]',
    );
    const gameName = await newPage.evaluate(btn => btn.textContent, btn);
    if (gameName.includes('Unlock')) {
      const pass = await newPage.$(
        'input[type="password"]',
      );
      await pass.click({ clickCount: 3 });
      await pass.type(psw);
    }
    if (gameName.includes('Send') || gameName.includes('Faucet')) {
      return;
    }
    await btn.click();
  } catch (e) {
    console.log(e);
  }
}

async function disConnect(newPage, psw) {
  await newPage.goto('chrome-extension://dldjpboieedgcmpkchcjcbijingjcgok/popup.html#/wallet');
  await sleep(1000);
  await unlock(newPage, psw);
  await sleep(3000);

  //解除关联
  const button = await newPage.$(
    'button[aria-label="Menu"]',
  );
  await button.click();
  await sleep(1000);
  const Menu = await newPage.$(
    'li[data-key="connected-apps"]',
  );
  await Menu.click();
  await sleep(1000);

  const dels = await newPage.$$(
    'button[aria-label="Delete"]',
  );
  for (const item of dels) {
    await item.click();
    await sleep(1000);
    const con = await newPage.$(
      'button[aria-label="Confirm delete"]',
    );
    await con.click();
    await sleep(1000);
  }

  return newPage;
}

function sleep(ms) {
  return new Promise(resolve => {
    setTimeout(resolve, ms);
  });
}

module.exports.exportAddresses = exportAddresses;
module.exports.refreshAccount = refreshAccount;
module.exports.startGame = startGame;
